package com.zsrt.oa.order.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zsrt.oa.order.dao.OrderDao;
import com.zsrt.oa.order.entity.OrderEntity;
import com.zsrt.utils.DBUtils;

/**
 * 订单的实现类
 * @author 罗智壕-13424431416
 *
 * 2017年6月11日
 */
public class OrderDaoImpl implements OrderDao {
	
	/**
	 * 创建订单
	 * @param entity
	 * @return
	 */
	@Override
	public int orderAdd(OrderEntity entity) throws SQLException{
		int counter = 0;
		Connection con = DBUtils.getMessage();
		String sql = "INSERT INTO tkt_order_t (user_id,ticket_id,order_time) VALUES(?,?,sysdate())";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, entity.getUserId());
		ps.setString(2, entity.getTicketId());
		
		counter = ps.executeUpdate();
		
		DBUtils.closeResources(con, ps);
		return counter;
	}
	
	/**
	 * 查询当前用户所有的订单
	 * @param entity
	 * @return
	 * @throws SQLException
	 */
	@Override
	public List<OrderEntity> myOrderMessage(OrderEntity entity) throws SQLException {
		List<OrderEntity> list = new ArrayList<OrderEntity>();
		Connection con = DBUtils.getMessage();
		String sql = "select "
				+ " order_id as orderId,"
				+ " ticket_id as ticketId,"
				+ " user_id as userId,"
				+ " order_time as orderTime,"
				+ " ticket_qty as ticketQty "
				+ " from tkt_order_t  "
				+ " where user_id = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, entity.getUserId());
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			OrderEntity orderEntity = new OrderEntity();
			orderEntity.setOrderId(rs.getString("orderId"));
			orderEntity.setTicketId(rs.getString("ticketId"));
			orderEntity.setUserId(rs.getString("userId"));
			orderEntity.setOrderTime(rs.getString("orderTime"));
			orderEntity.setTicketQty(rs.getInt("ticketQty"));
			list.add(orderEntity);
		}
		DBUtils.closeResources(con, ps, rs);
		return list;
	}
	
	/**
	 * 返回当前订单最大的id
	 * @return
	 * @throws SQLException
	 */
	@Override
	public int currentOrderId() throws SQLException {
		int counter = 0;
		Connection con = DBUtils.getMessage();
		String sql = "select order_id as orderId"
				+ " from tkt_order_t "
				+ " order by order_id desc LIMIT 1";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			counter = rs.getInt("orderId");
		}
		DBUtils.closeResources(con, ps, rs);
		return counter;
	}
}
